import sys
import pprint
import string
import sys
import cgi
import types
import traceback
import urllib

import genx_helpers
genx_helpers.add_module('pyecs')

import genx_metaweb
import genx_transfill
import genx_errors
import bm_text
import bm_extract
import bm_cfg

import api_ecs

from bm_log import Log

searchd = {
	"title" : "Books",
	"source" : "Amazon.com",
	"templated" : {
		"gencard-uf" : {
			"title" : "GenCard",
			"title_full" : "GenCard for Microformats",
			"caps" : [ 
				genx_helpers.CAP_GENCARD, 
				genx_helpers.CAP_HTML, 
				genx_helpers.CAP_MICROFORMATS, 
				genx_helpers.CAP_HITEM,
			],
		},
	},
}

CACHE = False
MAX_RESULTS = 30

def query(cfg, searchd, name, application, retry = 0):
	amazon = api_ecs.AmazonECS(
		AWSAccessKeyId = bm_cfg.cfg.as_string("amazon.AccessKeyID"),
		Locale = bm_cfg.cfg.as_string("amazon.Locale"),
		AssociateTag = bm_cfg.cfg.as_string("amazon.AssociateTag"),
	)
	amazon.SetRequest(
		Keywords = name,
		SearchIndex = "Books",
		Condition = "New",
		ResponseGroup = "Large",
	)

	Log(
		AccessKeyID = bm_cfg.cfg.as_string("amazon.AccessKeyID"),
		Locale = bm_cfg.cfg.as_string("amazon.Locale"),
		AssociateTag = bm_cfg.cfg.as_string("amazon.AssociateTag"),
		Keywords = name,
		SearchIndex = "Books",
		Condition = "New",
		ResponseGroup = "Large",
	)
		
	count = 0
	max = bm_cfg.cfg.as_int("amazon.max", otherwise = MAX_RESULTS)

	for resultd in amazon.IterItems():
		count += 1

		iid = application.MakeIID('%s@amazon.books' % bm_extract.extract(resultd, 'ASIN'))
		rd = {
			genx_helpers.KEY_IID : iid,
			genx_helpers.KEY_TITLE_SHORT : bm_extract.as_string(resultd, "ItemAttributes.Title"),
			genx_helpers.KEY_TITLE_FULL : bm_extract.as_string(resultd, "ItemAttributes.Title"),
			"author" : bm_extract.as_string(resultd, "ItemAttributes.Author"),
		}

		for keyt in [ 
			( 'ItemAttributes.PublicationDate', 'released', ),
			( 'ItemAttributes.Publisher', 'publisher', ),
			( 'ItemAttributes.EAN', 'EAN', ),
			( 'ItemAttributes.ISBN', 'ISBN', ),
			( 'DetailPageURL', 'amazon_uri', ),
			( 'ItemAttributes.DeweyDecimalNumber', 'DeweyDecimalNumber', ),
		]:
			value = bm_extract.as_string(resultd, keyt[0])
			if value and type(value) in types.StringTypes and value.strip():
				rd[keyt[1]] = value.strip()

		review = bm_extract.as_string(resultd, "EditorialReviews.EditorialReview.Content[0]")
		if review:
			review = bm_text.scrub_html(review)
			review = review.strip()
			if review:
				rd["description"] = review

		image_uri = bm_extract.as_string(resultd, "TinyImage.URL", separator = None)
		if not image_uri:
			image_uri = bm_extract.as_string(resultd, "SmallImage.URL", separator = None)
		if image_uri:
			rd[genx_helpers.KEY_IMAGE_URI] = image_uri

		rd[genx_helpers.KEY_TITLE_LIST] = "%s - %s%s" % (
			rd[genx_helpers.KEY_TITLE_FULL] or rd[genx_helpers.KEY_TITLE_SHORT] or "[no title]",
			rd["author"] or "[no author]",
			rd.get("released") and ( " [%s]" % rd["released"][:4] ) or "",
		)

		yield	rd

		if count >= max:
			break

